package com.xbongbong.workflow.service.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.exception.WorkflowException;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.help.ConditionListHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.pojo.vo.LinkResultDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.workflow.WorkflowDataPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.HookMethodUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.WorkflowUtil;
import com.xbongbong.parent.util.LinkDataUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.businessrule.enums.RuleValueTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.workflow.WorkflowValueTypeEnum;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.util.AddressUtil;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.FilterCondition;
import com.xbongbong.workflow.pojo.WorkflowOperationsPojo;
import com.xbongbong.workflow.pojo.WorkflowRulePojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.nodes.InsertRecordNode;
import com.xbongbong.workflow.service.field.WorkflowConditionFieldService;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @date 2021/06/08 16:56
 */
@Component
public class WorkflowDataNodeHelp {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowDataNodeHelp.class);


    @Resource
    private Map<Integer, WorkflowConditionFieldService> workflowConditionFieldMap;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;

    /**
     * 获取条件
     * @param filterCondition 过滤条件
     * @param fieldMap 目标表单的字段集合
     * @param explainMap 字段集合
     * @param paasFormDataEntity 本表数据
     * @param workflowRulePojo 关联数据存储
     * @param workflowNodeEntity
     * @param subConditionList
     * @param conditionList
     * @throws XbbException
     */
    public void getConditionList(List<FilterCondition> filterCondition, Map<String, FieldAttrEntity> fieldMap, Map<String, Map<String, FieldAttrEntity>> explainMap,
                                     PaasFormDataEntityExt paasFormDataEntity, WorkflowRulePojo workflowRulePojo,
                                    WorkflowNodeEntity workflowNodeEntity, List<ConditionsEntityExt> subConditionList, List<ConditionsEntityExt> conditionList) throws XbbException {
        try {

            for (FilterCondition item : filterCondition) {
                String targetAttr = item.getAttr();
                List<String> targetAttrArray = ExplainUtil.getAttrByPoint(targetAttr);
                String targetSubAttr = "";
                if (targetAttrArray.size() == 2) {
                    targetAttr = targetAttrArray.get(0);
                    workflowRulePojo.setParentAttr(targetAttr);
                    targetSubAttr = targetAttrArray.get(1);
                }
                FieldAttrEntity targetField = fieldMap.get(targetAttr);

                if (Objects.isNull(targetField)) {
                    //  字段不存在
                    throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                }
                if (Objects.equals(item.getValueType(), RuleValueTypeEnum.DYNAMIC_VALUE.getType())) {
                    String thisAttr = item.getValueAttr();
                    if (StringUtil.isEmpty(thisAttr)) {
                        //  字段不存在
                        throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                    }
                    List<String> thisAttrList = ExplainUtil.getAttrByPoint(thisAttr);
                    if (thisAttrList.size() == 2) {
                        thisAttr = thisAttrList.get(0);

                    }
                    Map<String, FieldAttrEntity> thisExplainMap;
                    FieldAttrEntity fieldAttrEntity;
                    if (Objects.equals(item.getTargetBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                        thisExplainMap = explainMap.get(PaasConstant.WORK_ORDER + item.getTargetFormId());
                        fieldAttrEntity = thisExplainMap.get(thisAttr);
                    } else {
                        thisExplainMap = explainMap.get(item.getTargetFormId().toString());
                        fieldAttrEntity = thisExplainMap.get(thisAttr);
                    }
                    if (Objects.isNull(fieldAttrEntity)) {
                        //  字段不存在
                        throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                    }
                    if (ExplainUtil.isSubForm(targetField.getFieldType())) {
                        // 目标表单为子表单的字段时
                        List<? extends FieldAttrEntity> jsonArray = targetField.getSubForm().getItems();
                        Map<String, FieldAttrEntity> targetSubExplainMap = ExplainUtil.getExplainMapByList(jsonArray);
                        targetField = targetSubExplainMap.get(targetSubAttr);
                        Integer targetFieldType = targetField.getFieldType();
                        Object object = getValueByData(fieldAttrEntity, targetField, paasFormDataEntity,  workflowRulePojo,
                                thisExplainMap,workflowNodeEntity, item, thisAttrList);
                        ConditionsEntityExt conditionsEntityExt =  setCondition(targetSubAttr,  targetFieldType, item, object, paasFormDataEntity.getId(), targetField.getDateType());
                        subConditionList.add(conditionsEntityExt);
                    } else {
                        Object object = getValueByData(fieldAttrEntity, targetField, paasFormDataEntity, workflowRulePojo, thisExplainMap, workflowNodeEntity, item, thisAttrList);
                        ConditionsEntityExt conditionsEntityExt = setCondition(targetAttr,  targetField.getFieldType(), item, object,  paasFormDataEntity.getId(), targetField.getDateType());
                        conditionList.add(conditionsEntityExt);
                    }
                } else {
                    if (ExplainUtil.isSubForm(targetField.getFieldType())) {
                        // 目标表单为子表单的字段时
                        List<? extends FieldAttrEntity> jsonArray = targetField.getSubForm().getItems();
                        Map<String, FieldAttrEntity> targetSubExplainMap = ExplainUtil.getExplainMapByList(jsonArray);
                        targetField = targetSubExplainMap.get(targetAttr);
                        if (Objects.isNull(targetField)) {
                            // TODO 字段不存在 记录日志
                            return;
                        }
                        Integer targetSubFieldType = targetField.getFieldType();
                        WorkflowConditionFieldService conditionFieldHandler = workflowConditionFieldMap.get(targetSubFieldType);
                        Object object = conditionFieldHandler.handlerFixedValue(targetField, workflowNodeEntity, item);
                        ConditionsEntityExt conditionsEntityExt = setCondition(targetSubAttr,  targetSubFieldType, item, object, paasFormDataEntity.getId(), targetField.getDateType());
                        subConditionList.add(conditionsEntityExt);
                    } else {
                        WorkflowConditionFieldService conditionFieldHandler = workflowConditionFieldMap.get(targetField.getFieldType());
                        Object object = conditionFieldHandler.handlerFixedValue(targetField, workflowNodeEntity, item);
                        ConditionsEntityExt conditionsEntityExt = setCondition(targetAttr,  targetField.getFieldType(), item, object, paasFormDataEntity.getId(), targetField.getDateType());
                        conditionList.add(conditionsEntityExt);
                    }
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("WorkflowNodeSingleDataStrategy.getConditionList error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    public Map<String, PaasFormDataEntityExt> getLinkDataMap(PaasFormDataEntityExt paasFormDataEntity, String corpid, Map<String, Map<String, FieldAttrEntity>> explainMap) throws XbbException {

        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (explainMap.isEmpty()) {
            return formDataMap;
        }
        for (Map.Entry<String, Map<String, FieldAttrEntity>> entry : explainMap.entrySet()) {
            Map<String, FieldAttrEntity> value = entry.getValue();
            List<FieldAttrEntity> explainList = new ArrayList<>();
            value.forEach((attr, field) -> {
                explainList.add(field);
            });
            formDataMap.putAll(getFormDataMap(paasFormDataEntity, corpid, explainList));
        }
        return formDataMap;
    }

    /**
     * 获取关联数据字段的数据
     */

    private Map<String, PaasFormDataEntityExt> getFormDataMap(PaasFormDataEntityExt paasFormDataEntity, String corpid, List<FieldAttrEntity> explainList) throws XbbException{
        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // todo
        Map<String, LinkInfoPojo> linkInfoPojoMap = LinkDataUtil.getLinkInfoMap(explainList);
        if (linkInfoPojoMap.isEmpty()) {
            return formDataMap;
        }
        JSONObject data = paasFormDataEntity.getData();
        Iterator<String> iterator = linkInfoPojoMap.keySet().iterator();
        Set<Object> dataSet = new HashSet<>();
        while (iterator.hasNext()) {
            String key = iterator.next();
            List<String> attrList = ExplainUtil.getAttrByPoint(key);
            if (attrList.size() == 2) {
                key = attrList.get(0);
                JSONArray subDataList = data.getJSONArray(key);
                if (Objects.nonNull(subDataList)) {
                    String subKey = attrList.get(1);
                    for (int i = 0; i < subDataList.size(); i++) {
                        JSONObject subData = subDataList.getJSONObject(i);
                        if (HookMethodUtil.isLegalData(subData, subKey)){
                            dataSet.add(subData.get(subKey));
                        }
                    }
                }
            } else if (HookMethodUtil.isLegalData(data, key)){
                dataSet.add(data.get(key));
            }
        }
        if (dataSet.isEmpty()) {
            return formDataMap;
        }
        LinkResultDataDTO linkResultDataDTO = new LinkResultDataDTO();
        linkResultDataDTO.setSearchUserTeam(false);
        linkResultDataDTO.setCorpid(corpid);
        LinkResultDataVO linkResultDataVO = new LinkResultDataVO();
        linkResultDataVO.setExplainList(explainList);
        linkResultDataVO.setLinkDataSet(dataSet);
        formDataMap = proFormHelp.ruleGetLinkDataOfBusinessType(linkResultDataDTO, linkResultDataVO);
        return formDataMap;
    }
    /**
     * 根据当前的字段类型获取数据
     * @param fieldAttrEntity 当前表单字段属性
     * @param targetField 目标表单字段属性
     * @param paasFormDataEntity 当前表单数据
     * @param workflowRulePojo
     * @param thisExplainMap 本表单字段解释
     * @param filterCondition 过滤条件
     * @param thisAttrArray 子表单字段，格式为["subForm_1", "text_1"] 由格式subForm_1.text_1解析而来
     * @return
     * @throws XbbException
     */
    public Object getValueByData(FieldAttrEntity fieldAttrEntity, FieldAttrEntity targetField, PaasFormDataEntityExt paasFormDataEntity,
                                 WorkflowRulePojo workflowRulePojo, Map<String, FieldAttrEntity> thisExplainMap, WorkflowNodeEntity workflowNodeEntity, FilterCondition filterCondition,
                                 List<String> thisAttrArray) throws XbbException {
        // 当前表单数据
        Integer targetFieldType = targetField.getFieldType();
        JSONObject data= paasFormDataEntity.getData();
        String thisAttr = fieldAttrEntity.getAttr();
        Object object = null;
        if (ExplainUtil.isSubForm(fieldAttrEntity.getFieldType())) {
            if (Objects.isNull(data.get(fieldAttrEntity.getAttr()))) {
                // 子表单无数据
                return null;
            }
            String thisSubAttr = thisAttrArray.get(1);
            Set<Object> valueSet = new HashSet<>();
            // 本表单是子表单时
            List<? extends FieldAttrEntity> thisSubForm = fieldAttrEntity.getSubForm().getItems();
            Map<String, FieldAttrEntity> thisSubExplainMap = ExplainUtil.getExplainMapByList(thisSubForm);
            FieldAttrEntity subFieldAttrEntity = thisSubExplainMap.get(thisSubAttr);
            JSONArray valueArray = data.getJSONArray(thisAttr);
            WorkflowConditionFieldService conditionFieldHandler;
            // 当前表单数据解析
            Object thisValue = getValueByFieldType(fieldAttrEntity, targetField, paasFormDataEntity, workflowRulePojo, thisAttrArray, thisSubExplainMap, workflowNodeEntity, filterCondition);
            List<Object> thisValueList = JSON.parseArray(JSON.toJSONString(thisValue), Object.class);
            for (int i = 0; i < thisValueList.size(); i++) {
                thisValue = thisValueList.get(i);
                conditionFieldHandler = workflowConditionFieldMap.get(targetFieldType);
                Object value = conditionFieldHandler.handlerTargetFormField(thisValue, paasFormDataEntity, valueArray.getJSONObject(i), subFieldAttrEntity, targetField, workflowNodeEntity,
                        workflowRulePojo, filterCondition);
                if (Objects.equals(FieldTypeEnum.NUM.getType(), targetFieldType) && !(value instanceof Number) && !(value instanceof List)) {
                    // 当过滤条件为数字字段时，对比时仅需实际值相等即可，不需要匹配小数位数。
                    // 必须是数字类型， 否则不执行正则
                    return new ArrayList<>();
                }
                if (Objects.nonNull(value) && !(value instanceof List)) {
                    valueSet.add(value);
                } else if (value != null) {
                    valueSet.addAll(JSON.parseArray(JSON.toJSONString(value), Object.class));
                }
            }
            if (valueSet.size() > 1) {
                filterCondition.setSymbol(ConditionEnum.INCLUDE.getSymbol());
            }

            object = new ArrayList<>(valueSet);
        } else {
            // 本表单不是子表单时
            object = getValueByFieldType(fieldAttrEntity, targetField, paasFormDataEntity, workflowRulePojo, thisAttrArray, thisExplainMap, workflowNodeEntity, filterCondition);
            WorkflowConditionFieldService conditionFieldHandler = workflowConditionFieldMap.get(targetFieldType);
            object = conditionFieldHandler.handlerTargetFormField(object, paasFormDataEntity, paasFormDataEntity.getData(), fieldAttrEntity, targetField, workflowNodeEntity, workflowRulePojo, filterCondition);
        }
        return object;
    }

    /**
     * 根据字段获取当前表单的数据以及子表单的数据
     * @param fieldAttrEntity 当前表单字段
     * @param targetField 目标表单
     * @param paasFormDataEntity 当前数据
     * @param workflowNodeEntity
     * @param thisSubExplainMap 字段容器，也可以是子表单的容器
     * @return
     * @throws XbbException
     */
    private Object getValueByFieldType(FieldAttrEntity fieldAttrEntity, FieldAttrEntity targetField, PaasFormDataEntityExt paasFormDataEntity,
                                       WorkflowRulePojo workflowRulePojo, List<String> thisAttrArray, Map<String, FieldAttrEntity> thisSubExplainMap, WorkflowNodeEntity workflowNodeEntity, FilterCondition filterCondition) throws XbbException {
        Integer thisFieldType = fieldAttrEntity.getFieldType();
        JSONObject data = paasFormDataEntity.getData();
        // 本表单字段
        if (ExplainUtil.isSubForm(thisFieldType)) {
            String thisAttr = thisAttrArray.get(0);
            String thisSubAttr = thisAttrArray.get(1);
            fieldAttrEntity = thisSubExplainMap.get(thisSubAttr);
            thisFieldType = fieldAttrEntity.getFieldType();
            List<Object> list = new ArrayList<>();
            JSONArray jsonArray = data.getJSONArray(thisAttr);
            if (Objects.isNull(jsonArray)) {
                jsonArray = new JSONArray();
            }
            WorkflowConditionFieldService conditionFieldHandler;
            for (int i = 0; i < jsonArray.size(); i++) {
                conditionFieldHandler = workflowConditionFieldMap.get(thisFieldType);
                Object value = conditionFieldHandler.handlerThisFormField(paasFormDataEntity, jsonArray.getJSONObject(i), fieldAttrEntity, targetField, workflowNodeEntity, filterCondition, workflowRulePojo);
                list.add(value);
            }
            return list;
        } else {
            WorkflowConditionFieldService conditionFieldHandler = workflowConditionFieldMap.get(thisFieldType);
            return conditionFieldHandler.handlerThisFormField(paasFormDataEntity, data, fieldAttrEntity, targetField, workflowNodeEntity, filterCondition, workflowRulePojo);
        }
    }

    /**
     * 拼装搜索条件
     * @param attr
     * @param targetFieldType
     * @param filterCondition
     * @param object
     * @param dataId
     * @return
     * @throws XbbException
     */
    private ConditionsEntityExt setCondition(String attr, Integer targetFieldType, FilterCondition filterCondition, Object object, Long dataId, String dateType) throws XbbException {
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(attr, null, targetFieldType, filterCondition.getSymbol());
        conditionsEntityExt.setDateType(dateType);
        if (ConditionListHelp.isEmpty(object, targetFieldType)) {
            if ((Objects.equals(FieldTypeEnum.DATETIME.getType(), targetFieldType) || Objects.equals(FieldTypeEnum.ADDRESS.getType(), targetFieldType))
                    && (Objects.equals(conditionsEntityExt.getSymbol(), ConditionEnum.EMPTY.getSymbol()) || Objects.equals(conditionsEntityExt.getSymbol(), ConditionEnum.NOEMPTY.getSymbol()))) {
                // 日期字段、地址字段的为空不为空
                return conditionsEntityExt;
            } else {
                String symbol = ConditionEnum.EMPTY.getSymbol();
                if (Objects.equals(conditionsEntityExt.getSymbol(), ConditionEnum.NOEQUAL.getSymbol())) {
                    symbol = ConditionEnum.NOEMPTY.getSymbol();
                }
                conditionsEntityExt.setSymbol(symbol);
                return conditionsEntityExt;
            }
        }
        if (Objects.equals(FieldTypeEnum.NUM.getType(), targetFieldType) && !RegexUtil.isNumber(object.toString()) && !(object instanceof List)) {
            // 当过滤条件为数字字段时，对比时仅需实际值相等即可，不需要匹配小数位数。
            // 必须是数字类型， 否则不执行正则 TODO
            throw new WorkflowException();
        }

        if(object instanceof List){
            List<Object> list = JSON.parseArray(JSON.toJSONString(object), Object.class);
            conditionsEntityExt.setValue(list);
        } else if (Objects.equals(FieldTypeEnum.DATAID.getAlias(), filterCondition.getValueAttr())
                && Objects.nonNull(dataId)) {
            conditionsEntityExt.setValue(Collections.singletonList(dataId));
        } else {
            List<Object> list = new ArrayList<>();
            list.add(object);
            conditionsEntityExt.setValue(list);
        }
        return conditionsEntityExt;
    }

    public WorkflowDataPojo getExplainMap(WorkflowNodeEntity workflowNodeEntity, List<FilterCondition> filterConditions) throws XbbException{
        String corpid = workflowNodeEntity.getCorpid();
        Set<Long> formIdSet = new HashSet<>();
        Set<Long> workOrderFormIdSet = new HashSet<>();
        Set<Long> workflowNodeIdSet = new HashSet<>();
        boolean isWorkOrder =  Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), workflowNodeEntity.getBusinessType());
        if (isWorkOrder) {
            workOrderFormIdSet.add(workflowNodeEntity.getFormId());
        } else {
            formIdSet.add(workflowNodeEntity.getFormId());
        }
        setFormIdAndNodeId(filterConditions, workflowNodeIdSet, workOrderFormIdSet, formIdSet);

        WorkflowDataPojo workflowDataPojo = getExplainMap(workOrderFormIdSet, formIdSet, corpid);
        return workflowDataPojo;
    }

    public WorkflowDataPojo getExplainMapByOperator(InsertRecordNode insertRecordNode, WorkflowNodeEntity workflowNodeEntity, List<WorkflowOperationsPojo> operatorList) throws XbbException{
        String corpid = workflowNodeEntity.getCorpid();
        boolean isWorkOrder =  Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), workflowNodeEntity.getBusinessType());
        Set<Long> workOrderFormIdSet = new HashSet<>();
        Set<Long> formIdSet = new HashSet<>();
        if (isWorkOrder) {
            workOrderFormIdSet.add(workflowNodeEntity.getFormId());
        } else {
            formIdSet.add(workflowNodeEntity.getFormId());
        }
        if (Objects.equals(BasicConstant.TWO, insertRecordNode.getChooseDataSource())) {
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), insertRecordNode.getDataSourceBusinessType())) {
                workOrderFormIdSet.add(insertRecordNode.getDataSourceFormId());
            } else {
                formIdSet.add(insertRecordNode.getDataSourceFormId());
            }
        }
        setFormIdByOperator(operatorList, workOrderFormIdSet, formIdSet);

        return getExplainMap(workOrderFormIdSet, formIdSet, corpid);
    }

    private void setFormIdAndNodeId(List<FilterCondition> conditions, Set<Long> workflowNodeIdSet, Set<Long> workOrderFormIdSet, Set<Long> formIdSet) {
        conditions.forEach(item->{
            if (Objects.equals(RuleValueTypeEnum.DYNAMIC_VALUE.getType(), item.getValueType())) {
                workflowNodeIdSet.add(item.getTargetWorkflowNodeId());
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), item.getTargetBusinessType())) {
                    workOrderFormIdSet.add(item.getTargetFormId());
                } else {
                    formIdSet.add(item.getTargetFormId());
                }
            }
        });
    }

    private void setFormIdByOperator(List<WorkflowOperationsPojo> operatorList, Set<Long> workOrderFormIdSet, Set<Long> formIdSet ) {
        operatorList.forEach(item->{
            if (Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), item.getValueType())) {
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), item.getBusinessType())) {
                    workOrderFormIdSet.add(item.getFormId());
                } else {
                    formIdSet.add(item.getFormId());
                }
            } else if (Objects.equals(WorkflowValueTypeEnum.FORMULA.getType(), item.getValueType())) {
                // 公式解析
                String forumla = item.getFormulaInfo().getFormula();
                String[] formulaArray = RegexUtil.getFormulaAttr(forumla);
                for (int f = 0; f < formulaArray.length; f++) {
                    String formulaStr = formulaArray[f];
                    String[] list = WorkflowUtil.getAttrByFormula(formulaStr);
                    if (WorkflowUtil.validateFormula(list, formulaStr)) {
                        if (formulaStr.contains(XbbRefTypeEnum.WORK_ORDER.getAlias())) {
                            Long formId = Long.valueOf(list[2].replace(PaasConstant.WORK_ORDER, ""));
                            workOrderFormIdSet.add(formId);
                        } else {
                            Long formId = Long.valueOf(list[2]);
                            formIdSet.add(formId);
                        }
                    }
                }

            }
        });
    }

    public WorkflowDataPojo updateNodeGetExplainMap(List<FilterCondition> conditions, WorkflowNodeEntity workflowNodeEntity, List<WorkflowOperationsPojo> operatorList) throws XbbException{
        Set<Long> workOrderFormIdSet = new HashSet<>();
        Set<Long> formIdSet = new HashSet<>();
        String corpid = workflowNodeEntity.getCorpid();
        Set<Long> workflowNodeIdSet = new HashSet<>();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), workflowNodeEntity.getBusinessType())) {
            workOrderFormIdSet.add(workflowNodeEntity.getFormId());
        } else {
            formIdSet.add(workflowNodeEntity.getFormId());
        }
        setFormIdAndNodeId(conditions, workflowNodeIdSet, workOrderFormIdSet, formIdSet);
        setFormIdByOperator(operatorList, workOrderFormIdSet, formIdSet);
        return getExplainMap(workOrderFormIdSet, formIdSet, corpid);
    }

    private WorkflowDataPojo getExplainMap(Set<Long> workOrderFormIdSet, Set<Long> formIdSet, String corpid ) throws XbbException {
        Map<Long, Map<String, FieldAttrEntity>> explainMap = proFormHelp.getFormFieldMap(formIdSet, corpid);
        Map<Long, Map<String, FieldAttrEntity>> workOrderExplainMap = proFormHelp.getWorkOrderFormFieldMap(workOrderFormIdSet, corpid);
        WorkflowDataPojo workflowDataPojo = new WorkflowDataPojo();
        Map<String, Map<String, FieldAttrEntity>> thisExplainMap = setExplainMap(explainMap, workOrderExplainMap);
        workflowDataPojo.setExplainMap(thisExplainMap);
        workflowDataPojo.setCorpid(corpid);
        return workflowDataPojo;
    }

    private static Map<String, Map<String, FieldAttrEntity>> setExplainMap(Map<Long, Map<String, FieldAttrEntity>> explainMap, Map<Long, Map<String, FieldAttrEntity>> workOrderExplainMap) {
        Map<String, Map<String, FieldAttrEntity>> thisExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(explainMap)) {
            explainMap.forEach((key, value)->{
                thisExplainMap.put(key.toString(), value);
            });
        }
        if (Objects.nonNull(workOrderExplainMap)) {
            workOrderExplainMap.forEach((key, value)->{
                String formIdStr = PaasConstant.WORK_ORDER + key;
                thisExplainMap.put(formIdStr, value);
            });
        }
        return thisExplainMap;
    }

    public WorkflowDataPojo getDataList(Integer editedData, WorkflowNodeEntity workflowNodeEntity, List<FilterCondition> filterCondition, WorkflowTransferPOJO workflowTransferPOJO,
                                        String orderField, String order, Integer pageNum) throws XbbException {
        String corpid = workflowNodeEntity.getCorpid();
        Long formId = workflowNodeEntity.getFormId();
        boolean isWorkOrder =  Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), workflowNodeEntity.getBusinessType());
        // 获取字段解释
        WorkflowDataPojo workflowDataPojo = getExplainMap(workflowNodeEntity, filterCondition);
        Map<String, Map<String, FieldAttrEntity>> explainMap = workflowDataPojo.getExplainMap();
        PaasFormDataEntityExt paasFormDataEntity = WorkflowUtil.getFormData(workflowTransferPOJO);
        if (Objects.equals(0, editedData) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
            paasFormDataEntity = WorkflowUtil.setData(workflowTransferPOJO.getOldData().getId(), workflowTransferPOJO.getCorpid(), workflowTransferPOJO.getOldData());
        } else if (Objects.equals(2, editedData) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
            // 触发事件编辑前数据
            if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE_BATCH.getType())) {
                Data oldData = workflowTransferPOJO.getOldData();
                paasFormDataEntity = WorkflowUtil.setData(oldData.getId(), corpid, oldData.getData(), oldData.getFormId(), oldData.getSaasMark(), oldData.getBusinessType());
            } else {
                Data data = workflowTransferPOJO.getData();
                WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
                paasFormDataEntity = WorkflowUtil.setData(workflowBackupDataEntity.getDataId(), corpid, workflowBackupDataEntity.getData(), data.getFormId(), data.getSaasMark(), data.getBusinessType());
            }
        }
        // 获取关联数据
        Map<String, PaasFormDataEntityExt> formDataMap = getLinkDataMap(paasFormDataEntity, corpid, explainMap);
        WorkflowRulePojo workflowRulePojo = new WorkflowRulePojo();
        workflowRulePojo.setFormDataMap(formDataMap);
        Map<String, FieldAttrEntity> fieldMap;
        String formIdStr = formId.toString();
        if (isWorkOrder) {
            formIdStr = PaasConstant.WORK_ORDER + formIdStr;
        }
        fieldMap = explainMap.get(formIdStr);
        if (Objects.isNull(fieldMap)) {
            throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
        }
        List<ConditionsEntityExt> subConditionList = new ArrayList<>();
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        // 获取条件
        getConditionList(filterCondition, fieldMap, explainMap, paasFormDataEntity, workflowRulePojo, workflowNodeEntity, subConditionList, conditionList);
        // 根据条件去查数据
        Map<String, FieldAttrEntity> targetExplainMap;
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), workflowNodeEntity.getBusinessType())) {
            targetExplainMap = explainMap.get(PaasConstant.WORK_ORDER + workflowNodeEntity.getFormId());
        } else {
            targetExplainMap = explainMap.get(workflowNodeEntity.getFormId().toString());
        }
        List<PaasFormDataEntityExt> dataList = getDataListByEs(corpid, workflowNodeEntity.getFormId(), workflowNodeEntity.getBusinessType(), workflowNodeEntity.getSaasMark(),
                orderField, order, conditionList, new HashSet<>(),  targetExplainMap, pageNum);
        // 根据条件去查子数据
        List<PaasFormSubDataEntity> subDataList = getSubDataListByEs(corpid, workflowNodeEntity.getFormId(), workflowRulePojo.getParentAttr(), workflowNodeEntity.getBusinessType(),
                workflowNodeEntity.getSaasMark(), subConditionList, dataList);
        // 当前表单子表单字段更新目标表单子表单字段：子表单搜索条件不为空且主字段的条件不为空，且能够搜到数据，则需要去检索子表单数据；
        //当前主字段更新目标表单子表单字段： 子表单搜索条件不为空且主字段的条件为空，则需要去检索子表单数据；
        boolean searchSubFormData = CollectionsUtil.isEmpty(conditionList)
                || (CollectionsUtil.isNotEmpty(dataList) && CollectionsUtil.isNotEmpty(conditionList));
        if (CollectionsUtil.isNotEmpty(subConditionList) && searchSubFormData) {
            Set<Long> parentIdSet = new HashSet<>();
            subDataList.forEach(item->parentIdSet.add(item.getDataId()));
            if (CollectionUtils.isEmpty(dataList)) {
                dataList = getDataListByEs(corpid, workflowNodeEntity.getFormId(), workflowNodeEntity.getBusinessType(), workflowNodeEntity.getSaasMark(),
                        orderField, order, new ArrayList<>(), parentIdSet,  targetExplainMap, pageNum);
            }

        }

        // TODO 审批不允许编辑如何处理
        workflowDataPojo.setDataList(dataList);
        workflowDataPojo.setSubDataList(subDataList);
        workflowDataPojo.setConditionList(conditionList);
        workflowDataPojo.setConditionList(subConditionList);
        workflowDataPojo.setCorpid(workflowTransferPOJO.getCorpid());
        return workflowDataPojo;
    }
    /**
     * 根据条件查询数据
     * @param corpid
     * @param formId
     * @param businessType
     * @param saasMark
     * @param orderField
     * @param order
     * @param conditionList
     * @return java.util.List<com.xbongbong.pro.domain.entity.UpdateDataEntity>
     * @author 吴峰
     * @date 2020/9/29 15:58
     * @throws XbbException
     */
    public List<PaasFormDataEntityExt> getDataListByEs(String corpid, Long formId, Integer businessType, Integer saasMark, String orderField, String order,
                                                        List<ConditionsEntityExt> conditionList, Set<Long> dataIdList, Map<String, FieldAttrEntity> explainMap, Integer pageNum) throws XbbException {
        if (CollectionsUtil.isEmpty(conditionList) && CollectionUtils.isEmpty(dataIdList)) {
            return new ArrayList<>();
        }
        if (Objects.isNull(pageNum)) {
            pageNum = PaasConstant.PAGE_NUM;
        }
        // 地址查询条件封装
        List<List<ConditionsEntityExt>> shouldConditions = new ArrayList<>();
        AddressUtil.addressSearchCondition(conditionList, shouldConditions);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        // 地址查询条件封装
        EsUtil.parseShouldCondition(boolQueryBuilder, shouldConditions, "", corpid, businessType);
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery("formId", formId));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
        if (CollectionsUtil.isNotEmpty(conditionList)) {
            EsUtil.parseCondition(boolQueryBuilder, conditionList, "", corpid, businessType);
        }
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), businessType)) {
            boolQueryBuilder.filter(termQuery("logType", 0));
        } else {
            // 跟进记录不需要flowStatus条件，性能问题 by kaka
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.PASS.getType(), FlowStatusEnum.NOT_NEED_APPROVAL.getType())));
        }
        if (CollectionsUtil.isNotEmpty(dataIdList)) {
            boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID,  dataIdList));
        }
        BoolQueryBuilder boolQuery = boolQuery();
        if (StringUtil.isNotEmpty(orderField)) {
            FieldAttrEntity sortFieldEntity = explainMap.get(orderField);
            if (Objects.nonNull(sortFieldEntity)) {
                SortOrder sortOrder = SortOrder.DESC;
                if (Objects.equals(order, SortOrder.ASC.toString())) {
                    sortOrder = SortOrder.ASC;
                }
                if (orderField.contains(StringConstant.CROSS)) {
                    orderField = StringConstant.JSON_DATA + StringConstant.POINT + orderField;
                }
                FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(sortFieldEntity.getFieldType());
                if(FieldTypeEnum.TEXT.getEsalias().equals( fieldTypeEnum.getEsalias())){
                    if (Objects.equals(fieldTypeEnum, FieldTypeEnum.STAGE_THRUSTER)) {
                        orderField = StringConstant.JSON_DATA + StringConstant.POINT + PaasStageEnum.STAGE_ID.getAttr();
                    } else {
                        orderField = orderField + ".raw";
                    }
                }
                sourceBuilder.sort(new FieldSortBuilder(orderField).order(sortOrder));
            }
        } else {
            SortOrder sortOrder = SortOrder.DESC;
            String sortField = FieldTypeEnum.UPDATETIME.getAlias();
            sourceBuilder.sort(new FieldSortBuilder(sortField).order(sortOrder));
        }
        boolQueryBuilder.filter(boolQuery);
        sourceBuilder.query(boolQueryBuilder);


        return paasEsModel.list(sourceBuilder, indexTypeEnum, new ArrayList<>(), 1, pageNum);
    }

    /**
     * 根据条件查询数据
     * @param corpid
     * @param formId
     * @param businessType
     * @param saasMark
     * @param conditionList
     * @param dataList
     * @return java.util.List<com.xbongbong.pro.domain.entity.UpdateDataEntity>
     * @author 吴峰
     * @date 2020/9/29 15:58
     * @throws XbbException
     */
    public List<PaasFormSubDataEntity> getSubDataListByEs(String corpid, Long formId, String parentAttr, Integer businessType, Integer saasMark,
                                                           List<ConditionsEntityExt> conditionList, List<PaasFormDataEntityExt> dataList) throws XbbException {
        if (CollectionsUtil.isEmpty(conditionList)) {
            return new ArrayList<>();
        }

        if (dataList.size() > PaasConstant.LIMIT_MAX_NUM) {
            // 如果大于这个数量的话，就没必要查了
            return new ArrayList<>();
        }
        Set<Long> parentIdList = new HashSet<>();
        dataList.forEach(item->{
            parentIdList.add(item.getDataId());
        });

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        if (StringUtil.isNotEmpty(parentAttr)) {
            boolQueryBuilder.filter(termQuery(StringConstant.ATTR + StringConstant.POINT + StringConstant.KEY_WORD, parentAttr));
        }
        if (CollectionsUtil.isNotEmpty(parentIdList)) {
            // 只有子表单，没有主数据，需要根据子表单的data_id反查主数据
            boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, parentIdList));
        }

        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery("formId", formId));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        EsUtil.parseCondition(boolQueryBuilder, conditionList, "", corpid, businessType);
        BoolQueryBuilder boolQuery = boolQuery();
        boolQueryBuilder.filter(boolQuery);

        IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, businessType, saasMark);

        List<PaasFormSubDataEntity> subDataList = paasFormSubDataEsModel.getSubDataList(boolQueryBuilder, indexTypeEnum, new ArrayList<>(), 1, 101, PaasFormSubDataEntity.class);
        if (subDataList.size() > PaasConstant.BUSINESS_RULE_SUB_FORM_MAX_LARGE) {
            return new ArrayList<>();
        }
        return subDataList;
    }
}
